package com.jin10.schedule;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient;
import com.jin10.bean.BaseResponse;
import com.jin10.bean.DingParams;
import com.jin10.bean.EconomicsResponse;
import com.jin10.constant.Global;
import com.jin10.constant.TitleHandlerClassMap;
import com.jin10.constant.TitleIndicatorId;
import com.jin10.dto.ParagraphDto;
import com.jin10.entity.PublishCalendar;
import com.jin10.entity.TitleHistory;
import com.jin10.service.IPublishCalendarService;
import com.jin10.service.ISentenceLibraryService;
import com.jin10.service.ITitleHandlerService;
import com.jin10.service.ITitleHistoryService;
import com.jin10.service.impl.USNonFarmPayrollsHandler;
import com.jin10.service.impl.USNonFarmUnemploymentRateHandler;
import com.jin10.util.DingTalk;
import com.jin10.util.Md5;
import com.jin10.vo.TagTreeVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author raofy
 * @date 2022-01-24 17:45
 * @desc
 */
@Component
public class MonitorCalendar {
    private static final Logger log = LoggerFactory.getLogger(MonitorCalendar.class);
    private static final String URL = "https://cdn-rili.jin10.com/web_data/%s/daily/%s/%s/economics.json";

    @Autowired
    ISentenceLibraryService iSentenceLibraryService;

    @Autowired
    TitleHandlerClassMap titleHandlerClassMap;

    @Autowired
    ITitleHistoryService iTitleHistoryService;

    @Autowired
    IPublishCalendarService iPublishCalendarService;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void requestMethod() {
        log.info("请求日历数据！！");
        DateTime current = DateUtil.date();
        int year = current.year();
        int month = current.month();
        int day = current.dayOfMonth();
        String url = String.format(URL, year, getMonth(month), getDay(day));
        String body = HttpRequest.get(url).execute().body();
        List<EconomicsResponse> response = JSON.parseArray(body, EconomicsResponse.class);
        // 监测非农数据 indicator_id = 75
        // 判断是否已经公布 actual != null
        StringBuffer stringBuffer = new StringBuffer();
        if (!response.isEmpty()) {
            for (EconomicsResponse economicsResponse : response) {
                if (Objects.nonNull(economicsResponse.getIndicatorId())) {
                    if (economicsResponse.getIndicatorId() == TitleIndicatorId.US_NON_FARM_PAYROLLS || economicsResponse.getIndicatorId() == TitleIndicatorId.US_NON_FARM_UNEMPLOYMENT_RATE) {
                        PublishCalendar one = iPublishCalendarService.getOne(new LambdaQueryWrapper<PublishCalendar>().eq(PublishCalendar::getReleaseTimeYear, year).eq(PublishCalendar::getReleaseTimeMonth, year).eq(PublishCalendar::getReleaseTimeDay, day));
                        if (Objects.isNull(one)) {
                            one = new PublishCalendar();
                        }
                        one.setTitleId(1);
                        one.setReleaseTimeYear(year);
                        one.setReleaseTimeMonth(month);
                        one.setReleaseTimeDay(day + 1);
                        if (Objects.nonNull(economicsResponse.getActual())) {
                            one.setPublished(true);
                        }else {
                            one.setPublished(false);
                        }
                        try {
                            iPublishCalendarService.saveOrUpdate(one);
                        } catch (Exception e) {
                            requestMethod();
                        }
                    }
                }

            }
        }

//        if (stringBuffer.length() > 0) {
//            // 判断是否历史已经发送，并持久化到本地数据表
//            String md5 = Md5.string2Md5(stringBuffer.toString());
//            int count = iTitleHistoryService.count(new LambdaQueryWrapper<TitleHistory>().eq(TitleHistory::getDate, DateUtil.today()).eq(TitleHistory::getMd5, md5));
//            if (count == 0) {
//                // 保存并发表
//                TitleHistory titleHistory = new TitleHistory();
//                titleHistory.setDate(DateUtil.today());
//                titleHistory.setMd5(md5);
//                titleHistory.setTitile(stringBuffer.toString());
//                iTitleHistoryService.save(titleHistory);
//                DingTalk.sendToGroup(stringBuffer.toString());
//                log.info("发布的文章：{}", stringBuffer.toString());
//            } else {
//                // 如果重复，重新抓取整合
//                requestMethod();
//            }
//
//        }

//        if (send1 && send2) {
//            stringBuffer.append("\n" + getAssetAnalysis());
//            log.info("发送内容为{}", stringBuffer.toString());
//            DingTalk.sendToGroup(stringBuffer.toString());
//        }

    }

    public String getMonth(int month) {
        String[] months = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
        return months[month];
    }

    public String getDay(int day) {
        String[] days = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13",
                "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
        return days[day];
    }


    /**
     * 比较非农数据 整合句子
     *
     * @param economicsResponse
     * @return
     */
    public String getNonFarm(EconomicsResponse economicsResponse, int year, String month, String day) {
        StringBuffer stringBuffer = new StringBuffer();
        // 获取当前非农数据的公布值
        Float actual = Float.valueOf(economicsResponse.getActual().toString());
        // 请求接口获取最值
        Float max = new Float(0.0);
        Float min = new Float(0.0);
        // 预期值与公布值比较
        Float consensus = Float.valueOf(economicsResponse.getConsensus().toString());
        if (actual > consensus) {
            ParagraphDto paragraphDto = new ParagraphDto();
            paragraphDto.setTagIds(Arrays.asList(17));
            List<TagTreeVo> sentenceLibraryByTag = (List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto);
            List<String> strings = diGuiShengChengWenZhang(sentenceLibraryByTag, new StringBuffer());
            stringBuffer.append(String.format("%s年%s美国非农新增就业人数为%s万人，高于市场预期的%s万人; %s", Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), actual, consensus, strings.get(0)));
        } else if (actual < consensus) {
            ParagraphDto paragraphDto = new ParagraphDto();
            paragraphDto.setTagIds(Arrays.asList(19));
            List<TagTreeVo> sentenceLibraryByTag = (List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto);
            List<String> strings = diGuiShengChengWenZhang(sentenceLibraryByTag, new StringBuffer());
            stringBuffer.append(String.format("%s年%s美国非农新增就业人数为%s万人，低于市场预期的%s万人; %s", Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), actual, consensus, strings.get(0)));
        } else {
            ParagraphDto paragraphDto = new ParagraphDto();
            paragraphDto.setTagIds(Arrays.asList(18));
            List<TagTreeVo> sentenceLibraryByTag = (List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto);
            List<String> strings = diGuiShengChengWenZhang(sentenceLibraryByTag, new StringBuffer());
            stringBuffer.append(String.format("%s年%s美国非农新增就业人数为%s万人，基本符合市场预期的%s万人; %s", Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), actual, consensus, strings.get(0)));
        }
        return String.format("%s\n", stringBuffer.toString());
    }

    /**
     * 失业率比较
     *
     * @param economicsResponse
     * @return
     */
    public String getJoblessRate(EconomicsResponse economicsResponse, int year, String month, String day) {
        StringBuffer stringBuffer = new StringBuffer();
        // 获取当前非农数据的公布值
        Float actual = Float.valueOf(economicsResponse.getActual().toString());
        // 预期值与公布值比较
        Float consensus = Float.valueOf(economicsResponse.getConsensus().toString());
        // 前值
        Float previous = Float.valueOf(economicsResponse.getPrevious().toString());
        if (actual > consensus) {
            ParagraphDto paragraphDto = new ParagraphDto();
            paragraphDto.setTagIds(Arrays.asList(22));
            List<TagTreeVo> sentenceLibraryByTag = (List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto);
            List<String> strings = diGuiShengChengWenZhang(sentenceLibraryByTag, new StringBuffer());
            stringBuffer.append(String.format("%s失率数为%s%%，高于市场预期的%s%%，%s前值%s%%； %s", economicsResponse.getTimePeriod(), actual, consensus, previous > actual ? "低于" : "高于", economicsResponse.getPrevious(), strings.get(0)));
        } else if (actual < consensus) {
            ParagraphDto paragraphDto = new ParagraphDto();
            paragraphDto.setTagIds(Arrays.asList(21));
            List<TagTreeVo> sentenceLibraryByTag = (List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto);
            List<String> strings = diGuiShengChengWenZhang(sentenceLibraryByTag, new StringBuffer());
            stringBuffer.append(String.format("%s失率数为%s%%，低于市场预期的%s%%，%s前值%s%%； %s", economicsResponse.getTimePeriod(), actual, consensus, previous > actual ? "低于" : "高于", economicsResponse.getPrevious(), strings.get(0)));
        } else {
            ParagraphDto paragraphDto = new ParagraphDto();
            paragraphDto.setTagIds(Arrays.asList(23));
            List<TagTreeVo> sentenceLibraryByTag = (List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto);
            List<String> strings = diGuiShengChengWenZhang(sentenceLibraryByTag, new StringBuffer());
            stringBuffer.append(String.format("%s月失率数为%s%%，高于市场预期的%s%%，%s前值%s%%； %s", economicsResponse.getTimePeriod(), actual, consensus, previous >= actual ? "低于等于" : "高于", economicsResponse.getPrevious(), strings.get(0)));
        }
        return String.format("%s%s%s，前值%s%s，预测值%s%s，实际值%s%s\n", economicsResponse.getCountry(), economicsResponse.getTimePeriod(), economicsResponse.getName(), economicsResponse.getPrevious(), economicsResponse.getUnit(), economicsResponse.getConsensus(), economicsResponse.getUnit(), economicsResponse.getActual(), economicsResponse.getUnit());
    }

    /**
     * 获取资产分析段落
     *
     * @return
     */
    public String getAssetAnalysis() {
        StringBuffer stringBuffer = new StringBuffer();
        ParagraphDto paragraphDto = new ParagraphDto();

        // 获取偏鸽子数据
        paragraphDto.setTagIds(Arrays.asList(38));
        List<String> piange = diGuiShengChengWenZhang((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer());

        // 获取纠结数据
        paragraphDto.setTagIds(Arrays.asList(39));
        List<String> jiujie = diGuiShengChengWenZhang((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer());

        // 获取偏鹰数据
        paragraphDto.setTagIds(Arrays.asList(40));
        List<String> pianying = diGuiShengChengWenZhang((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer());

        if (!piange.isEmpty()) {
            stringBuffer.append(String.format("鸽派结论: %s \n", piange.get(0)));
        }
        if (!jiujie.isEmpty()) {
            stringBuffer.append(String.format("纠结结论: %s \n", jiujie.get(0)));
        }
        if (!pianying.isEmpty()) {
            stringBuffer.append(String.format("鹰派结论: %s \n", pianying.get(0)));
        }
        return stringBuffer.toString();
    }


    public List<String> diGuiShengChengWenZhang(List<TagTreeVo> sentenceLibraryByTag, StringBuffer stringBuffer) {
        if (!sentenceLibraryByTag.isEmpty()) {
            ArrayList<String> titles = new ArrayList<>();
            for (TagTreeVo tagTreeVo : sentenceLibraryByTag) {
                returnTitle(tagTreeVo, stringBuffer);
                if (stringBuffer.length() > 0 && stringBuffer.charAt(stringBuffer.length() - 1) == '，') {
                    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                    stringBuffer.append("。");
                }
                titles.add(stringBuffer.toString());
                stringBuffer = new StringBuffer();
            }
            return titles;
        } else {
            return new ArrayList<>();
        }
    }

    public void returnTitle(TagTreeVo tagTreeVo, StringBuffer stringBuffer) {
        stringBuffer.append(tagTreeVo.getTitle());
        List<TagTreeVo> subclass = tagTreeVo.getSubclass();
        if (!StrUtil.isBlankIfStr(tagTreeVo.getTitle())) {
            stringBuffer.append("，");
        }
        if (subclass != null && !subclass.isEmpty()) {
            for (TagTreeVo treeVo : subclass) {
                returnTitle(treeVo, stringBuffer);
            }
        }
    }
}
